// 删除地址
const cloud = require('wx-server-sdk')

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const { addressId } = event
  
  // 直接使用openid作为用户标识
  if (!wxContext.OPENID) {
    return {
      success: false,
      message: '用户未登录'
    }
  }
  
  const userOpenid = wxContext.OPENID

  if (!addressId) {
    return {
      success: false,
      message: '地址ID不能为空'
    }
  }

  try {
    // 先查询要删除的地址信息
    const addressResult = await db.collection('addresses')
      .doc(addressId)
      .get()

    if (!addressResult.data) {
      return {
        success: false,
        message: '地址不存在'
      }
    }

    // 验证地址所有权
    if (addressResult.data.userId !== userOpenid) {
      return {
        success: false,
        message: '无权限删除此地址'
      }
    }

    // 删除地址
    await db.collection('addresses')
      .doc(addressId)
      .remove()

    // 如果删除的是默认地址，需要将其他地址中的第一个设为默认
    if (addressResult.data.isDefault) {
      const remainingAddresses = await db.collection('addresses')
        .where({
          userId: userOpenid
        })
        .orderBy('createTime', 'desc')
        .limit(1)
        .get()

      if (remainingAddresses.data.length > 0) {
        await db.collection('addresses')
          .doc(remainingAddresses.data[0]._id)
          .update({
            data: {
              isDefault: true,
              updateTime: new Date()
            }
          })
      }
    }

    return {
      success: true,
      message: '删除地址成功'
    }
  } catch (error) {
    console.error('删除地址失败:', error)
    return {
      success: false,
      message: '删除地址失败',
      error: error.message
    }
  }
}